<template>
	<scroll-view 
		scroll-y 
		@scrolltolower="onTolower"
		class="scroll-com">
		<slot></slot>
		<view class="load-state-container">
			<template v-if="loadState == 'init'">
				
			</template>
			<template v-if="loadState == 'loading'">
				<!--<van-loading color="{{theme.color}}" custom-class="loading-icon"></van-loading> -->
				<text class="text">正在加载中</text>
			</template>
			<template v-if="loadState == 'finished'">
				<text class="text">下拉加载</text>
			</template>
			<template v-if="loadState == 'nomore'">
				<text class="text">已经到底啦~</text>
			</template>
			<template v-if="loadState == 'nodata'">
				<text class="text">暂无数据</text>
			</template>
		</view>
	</scroll-view>
</template>

<script>
	export default {
		name:"scroll-com",
		emits: ['load'],
		props: ['api'],
		data() {
			return {
				page: {
					pageNo: 0,
					pageSize: 10
				},
				loadOption: {
					api: null,
					params: {}
				},
				loadState: 'init', //init,nodata,nomore,finished,loading
			}
		},
		methods: {
			/**
			 * 设置下拉加载配置
			 * @param {Object} option
			 * 	{
			 *		api:加载请求接口
			 * 		pageInfo: 分页信息
			 * 		params: 接口请求参数
			 *	}
			 */
			setLoadOption(option){
				this.loadOption = {
					...this.loadOption,
					...option
				}
				this.loadState = 'init'
				this.page.pageNo = 1
				this.loadPage({type: 'init'})
			},
			/**
			 * 滚动到底部
			 */
			onTolower(){
				if(this.loadOption.api){
					this.loadPage({type: 'load'})
				}
			},
			/**
			 * @param {Object} payload
			 * {
			 * 	 type: load加载|init初始化 
			 * }
			 */
			loadPage(payload){
				if(this.loadState == 'nodata' || this.loadState == 'nomore' || this.loadState == 'loading'){
					return
				}
				
				if(this.page.pageNo == 1){
					this.loadState = 'init'
				}else{
					this.loadState = 'loading'
				}
				
				
				let params = this.loadOption.params
				this.loadOption.api({
					...params,
					pageCurrent: this.page.pageNo,
					pageSize: this.page.pageSize
				}).then(reponse=>{
					let state = '';
					if(reponse.object.totalElements == 0){
						state = 'nodata';
					}else if(reponse.object.totalPages == this.page.pageNo){
						state = 'nomore';
					}else{
						state = 'finished';
					}
					setTimeout(()=>{
						reponse.scroll = {type: payload.type};
						this.$emit('load', reponse);
						this.loadState = state;
						this.page.pageNo = this.page.pageNo + 1;
					},500);
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.scroll-com{
		width: 100%;
		height: 100%;
		.load-state-container{
			display: flex;
			align-items: center;
			justify-content: center;
			height: 50px;
			box-sizing: border-box;
			.text{
				font-size: 14px;
				color: $text-desc-color;
			}
		}
	}
</style>